<?php
    class IndexController extends Main_Controller_Action
    {   
        public function init()
        {
            $this->loadTemplates();
            $db = Zend_Registry::get('db');
        }
        
        public function preDispatch()
        {
        	$request = new Zend_Controller_Request_Http();
            $emailCookie = $request->getCookie('emailUser');
            $passwordCookie = $request->getCookie('passwordUser');
            if(!empty($emailCookie))
            {
                $db = Zend_Registry::get('db');
                // 1. Khoi tao Zend_Auth
        		$auth = Zend_Auth::getInstance();
        		
        		// 2. Khai bao bang va 2 cot se su dung so sanh trong qua trinh login
        		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
        		$authAdapter->setTableName('user')
			        		->setIdentityColumn('email')
			        		->setCredentialColumn('password');
        		
        		// 3. Dua vao so sanh voi du lieu khai bao o muc 2
        		$authAdapter->setIdentity($emailCookie);
        		$authAdapter->setCredential($passwordCookie);
        		
        		// 4. Kiem tra level cua user neu level = 3 moi duoc login
        		$select = $authAdapter->getDbSelect();
        		$select->where('level = 3 AND status = 1');
        		
        		// 5. Lay ket qua truy van
        		$result = $auth->authenticate($authAdapter);
        		$flag = false;
        		if($result)
        		{
        			// 6. Lay nhung du lieu can thiet trong bang user neu login thanh cong
        			$data = $authAdapter->getResultRowObject();
                    $data->type_user = 'user';
        			// 7. Luu nhung du lieu cua member vao session
        			$auth->getStorage()->write($data);
        		}
            }
        }
        
        public function indexAction()
        {
            $this->view->headTitle("uMarket - Trang chủ");
            $category = new AdminDthink_Model_Category();
            $rows = $category->listVoucher(27);
			
			$this->view->data = $rows;
        }
        
        public function registerAction()
        {
            $this->view->headTitle("uMarket - Đăng ký");
            if ($this->_request->isPost())
            {
                $user = new Default_Model_User();
                $filter = new Zend_Filter_StringTrim();
                $email = $filter->filter($this->_request->getParam('email'));
                $password = $this->_request->getParam('password');
                $rePassword = $this->_request->getParam('rePassword');
                $fullname = $filter->filter($this->_request->getParam('fullname'));
                $gender = $this->_request->getParam('gender');
                $flag = true;
                $validate = new Default_Form_ValidateUser();
                 if($validate->validEmail($email))
                    {
                        $this->view->emailValue = $email;
                    }
                 else
                    {
                        $this->view->errorEmail = 'Địa chỉ email không hợp lệ';
                        $flag = false;
                    }
                 if($user->checkUser($email)>0)
                   {
                    $this->view->errorEmail = 'Địa chỉ Email này đã tồn tại';
                    $flag=false;
                    
                   }
                 if ($validate->validFullname($fullname))
                    {
                        $this->view->fullnameValue=$fullname;
                    }
                 else
                    {
                        $this->view->errorFullname='Tên đầy đủ không hợp lệ';
                        $flag=false;
                    }
                 if(!$validate->validPassword($password))
                    
                    {
                        $this->view->errorPassword='Mật khẩu phải từ 6-32 ký tự';
                    }
                 if (!$validate->validrepass($rePassword,$password))                    
                    {
                        $this->view->errorRepassword='Xác nhận mật khẩu sai';
                        $flag=false;
                    }
                if ($flag == true)
                {
                    $user->addUser($fullname,$email,$password,$gender);
                    $auth = Zend_Auth::getInstance();
                                        
                    $authAdapter = new Zend_Auth_Adapter_DbTable($db);
                    $authAdapter->setTableName('user')
                            ->setIdentityColumn('email')
                            ->setCredentialColumn('password');
                                                    
                    $authAdapter->setIdentity($email)
                            ->setCredential(md5($password));
                                                    
                    $select = $authAdapter->getDbSelect();
                    $select->where('level = 3 AND status = 1');
                    $result = $auth->authenticate($authAdapter);
                    if($result->isValid())
                        {
                            $data = $authAdapter->getResultRowObject(null, array('password'));
                            $auth->getStorage()->write($data);
                            $this->_redirect('index/success');
                        }
                    else
                        {
                            $this->_redirect('index/blockuser');
                        }
                }
                
            }
            
        }
        
        public function successAction()
        {
            $this->_helper->layout->setLayout('success_layout');
            $this->view->headTitle('uMarket - Đăng ký thành công');
            $auth = Zend_Auth::getInstance();
            $infoUser = $auth->getIdentity();
            $this->view->fullname = $infoUser->fullname;
        }
        
        public function loginAction()
        {
            $openSite = $this->_request->getParam('openSite');
            $muser = new Default_Model_User();
            if($openSite == 'facebook')
            {
                $facebook = new Facebook_Facebook(array(
                    //'appId' => '342584362497965',
                    //'secret' => '7c62e01337b9c5c94e2ec4325f57ce8c',
                    'appId' => '394487913951162',
                    'secret' => 'e28dbbaa57215f2dc517aade928e1dd2',
                    'cookie' => true,
                ));
                
                $adminAccessToken = $facebook->getAccessToken();
                
                if($userfb = $facebook->getUser())
                {
                    try
                    {
                        $fql    =   "select email, name from user where uid = ". $userfb;
                        $param  =   array(
                            'method'     => 'fql.query',
                            'query'     => $fql,
                            'access_token' => $adminAccessToken ,
                            'callback'    => ''
                        );
                        $user = $facebook->api($param);
                    }
                    catch(FacebookApiException $e)
                    {
                        $userfb      = null;
                        $UserProfile = null;
                    }
                    
                    if(!empty($user))
                    {
                        $user['email'] = $user['0']['email'];
                        $user['name'] = $user['0']['name'];
                        $user['type_user'] = 'facebook';
                        $user['level'] = 3;
                        $user = $muser->array_to_object($user);
                        $auth = Zend_Auth::getInstance();
                        $auth->getStorage()->write($user);
                        $this->_redirect('index/index');
                    }
                }
                else
                {
                    $login_url = $facebook->getLoginUrl(array('scope' => 'email'));
                    $this->_redirect($login_url);
                }
            }
            elseif($openSite == 'google')
            {
                $openId = new Google_LightOpenID('localhost:81/umarket');
                //$openId = new Google_LightOpenID('http://www.umarket.vn/');
                if(!$openId->mode)
                {
                    $openId->identity = 'https://www.google.com/accounts/o8/id';
                    $openId->required = array('namePerson/first', 'namePerson/last', 'contact/email');
                    $this->_redirect($openId->authUrl());
                }
                elseif($openId->mode == 'cancel')
                {
                    $this->_redirect('index/login');
                }
                else
                {
                    $user = $openId->getAttributes();
                    $user['first'] = $user['namePerson/first'];
                    $user['last'] = $user['namePerson/last'];
                    $user['email'] = $user['contact/email'];
                    $user['type_user'] = 'google';
                    $user['level'] = 3;
                    $user = $muser->array_to_object($user);
                    $auth = Zend_Auth::getInstance();
                    $auth->getStorage()->write($user);
                    $this->_redirect('index/index');
                }
            }
            else
            {
                $this->view->headTitle('uMarket - Đăng nhập');
                $email = $this->_request->getParam('email');
                $password = $this->_request->getParam('password');
                $rememberMe = $this->_request->getParam('rememberMe');

                if($this->_request->isPost())
                {
                    $validation = new Default_Form_ValidateUser();
                    $flag = true;
                    if(!$validation->validEmail($email))
                    {
                        $this->view->error = 'Sai tên đăng nhập hoặt mật khẩu!';
                        $flag = false;
                    }
                    if(!$validation->validPassword($password))
                    {
                        $this->view->error = 'Sai tên đăng nhập hoặt mật khẩu!';
                        $flag = false;
                    }
                    
                    if($flag == true)
                    {
                        $auth = Zend_Auth::getInstance();
                  		$authAdapter = new Zend_Auth_Adapter_DbTable($db);
                  		$authAdapter->setTableName('user')
               					->setIdentityColumn('email')
               					->setCredentialColumn('password');
                        $authAdapter->setIdentity($email);
                        $authAdapter->setCredential(md5($password));
            
                        $select = $authAdapter->getDbSelect();
                        $select->where('level = 3 AND status = 1');
                  		$result = $auth->authenticate($authAdapter);
                        if($result->isValid())
                        {
                            $data = $authAdapter->getResultRowObject();
         	        		$data->type_user = 'user';
                            $auth->getStorage()->write($data);
                            if($rememberMe == 1)
                            {
               					$expires = time() + 60 * 60 * 24 * 365;
               					setcookie('emailLogin', $data->email, $expires);
               					setcookie('passwordLogin', $data->password, $expires);
                            }
                            $this->_redirect('index/index');
                        }
                        else
                        {
                            $this->view->error = 'Sai tên đăng nhập hoặt mật khẩu!';
                        }
                    }
                }
            }
        }
        
        public function logoutAction()
        {
            $auth = Zend_Auth::getInstance();
            $auth->clearIdentity();
            
            $request = new Zend_Controller_Request_Http();
            $emailCookie = $request->getCookie('emailUser');
            $passwordCookie = $request->getCookie('passwordUser');

            setcookie('emailUser', null, -1);
            setcookie('passwordUser', null, -1);
            
            $this->_redirect('index/index');
        }
    }
